// index.js
// 获取应用实例
const app = getApp()
var WXBizDataCrypt = require('./WXBizDataCrypt.js')
Page({
  data: {
    navigationSetting: {
      title: '登录',
      height: app.globalData.navBarHeight,
      paddingTop: app.globalData.statusBarHeight,
      backgroundColor: 'white',
      size: 'default',
      back: ''
    },
    list: '',
    activeNum: 0,
    isSelected: false,
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
  },
  phoneLogin() {
    console.log(212)
    wx.navigateTo({
      url: '/pages/phone-login/phone-login',
    })
  },
  selBox(e) {
    this.setData({
      isSelected: !this.data.isSelected
    })
  },
  onTapButton() {
    if (!this.data.isSelected) {
      wx.showToast({
        title: '须先阅读并同意相关协议',
        icon: 'none',
        duration: 2000 //持续的时间
      })
      return false
    }
    this.setData({
      activeNum: 1
    })
    console.log(333)
  },
  gotoPrivateFile() {
    wx.navigateTo({
      url: '/pages/html/html?type=' + 1,
    })
  },
  gotoUserFile() {
    wx.navigateTo({
      url: '/pages/html/html?type=' + 2,
    })
  },
  wxLogin(e) {
    console.log(e)
    let iv = e.detail.iv
    let encryptedData = e.detail.encryptedData
    if (iv === undefined) {
      //拒绝
      wx.switchTab({
        url: '/pages/homepage/homepage',
      })
    } else {

      let loginCode = wx.getStorageSync('loginCode')
      let data = {
        loginCode: loginCode,
        ikey: iv,
        encryptedData: encryptedData
      }
      app.login.loginByWechat(data)
        .then(res => {
          console.log(99999)
          if (res.code === 200) {
            app.globalData.token = res.data
            wx.setStorageSync('token', res.data)
            wx.switchTab({
              url: '/pages/homepage/homepage',
            })
          } else if (res.code === 301) {

            console.log('进来了吗')
            wx.login({
              success: res => {
                wx.setStorageSync('loginCode', res.code)
                // 发送 res.code 到后台换取 openId, sessionKey, unionId
              }
            })
          }
          if (res.code != 200) {
            wx.showToast({
              title: '登录异常！',
              icon: 'none'
            })
          }
          console.log(res)
        })
        .catch(res => {
          wx.stopPullDownRefresh()
          wx.showToast({
            title: '出错了！',
            icon: 'none'
          })
        })

    }
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad() {
    wx.setStorageSync('token', null)
    // 登录
    wx.login({
      success: res => {
        wx.setStorageSync('loginCode', res.code)
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
  },
})